import Router from "koa-router";
import db from "./../models/db.js";
import jwt from "jsonwebtoken";
import koaJwt from "koa-jwt";

const router = new Router();
const secret = "secret";

// id 为可选参数
router.get("/:id?", (ctx, next) => {
    const userId = ctx.params.id;
    ctx.body = "routes/users.js --> get --> /" + `, 参数id:  ${userId}`;
});

router.post("/login", async (ctx, next) => {
    const { username, password } = ctx.request.body;
    const [rows] = await db.execute(`SELECT * FROM users WHERE username = '${username}' AND password = '${password}'`);
    let result = "routes/users.js --> post --> /login"
    if (rows.length) {
        result = result + `, 登录成功, 参数 ${JSON.stringify(rows)}`;
        const token = jwt.sign({ username }, secret, { expiresIn: '1h' });
        result = result + `, token ${token}`;
    } else {
        result = result + `, 用户未注册`;
    }
    ctx.body = result;
});

router.post("/userInfo", koaJwt({ secret }), async (ctx, next) => {
    const { token } = ctx.request.header;
    ctx.body = "routes/users.js --> post --> /userInfo" + `, 参数 ${token}`;
});

router.post("/logout", (ctx, next) => {
    const { username } = ctx.request.body;
    ctx.body = "routes/users.js --> post --> /logout" + `, 参数 ${username}`;
});

export default router;
